package controller.pub;

import controller.MyCoolServlet;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.*;
import javax.servlet.http.*;
import model.Product;
import persistence.product.ProductDAO;
import persistence.product.ProductPersistFactory;

public class AddToCarritoServlet extends MyCoolServlet {

    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ProductDAO persistenceManager = ProductPersistFactory.getProductDAO(persistenceMechanism);
        String productName = request.getParameter("nombre");
        Map<String, Product> productMap = new HashMap<String, Product>();
        persistenceManager.readProduct(productName, productMap);
        if (productMap.size()>0) {
            HttpSession s = request.getSession();
            if(s.getAttribute("carrito") == null)
                s.setAttribute("carrito", productMap);
            else{
                 Map<String, Product> carritoCompra = (HashMap) s.getAttribute("carrito");
                 carritoCompra.put(productName, productMap.get(productName));
                 s.setAttribute("carrito", carritoCompra);
            }
            gotoURL(carrito, request, response);
        } else {
            request.setAttribute("message1", "Carrito vacio:");
            request.setAttribute("message2", "Incluya productos pulsando en  \"AL CARRITO\" sobre el producto deseado");
            gotoURL(errorForm, request, response);
        }
    }
}